package com.ajz.security.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.ajz.common.utils.Collections3;
import com.ajz.security.entity.Role;
import com.google.common.base.Joiner;

/**
 * TOFIX: 直接继承User类，使用spring session后，拿到的principal为空
 * 
 * @author zhanghui
 * @create 2017年06月
 */
public class SecurityUser implements UserDetails {
	
	private static final long serialVersionUID = 1L;

	private String id;

	private String name;

	private String loginName;

	private String password;

	private String type;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	private List<Role> roles;

	private List<String> dataPermissions;

	public SecurityUser(String id, String name, String loginName, String password, List<Role> roles) {
		this.id = id;
		this.name = name;
		this.loginName = loginName;
		this.password = password;
		this.roles = roles;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		if (this.roles != null) {
			for (Role role : this.roles) {
				SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getName());
				authorities.add(authority);
			}
		}
		return authorities;
	}

	@Override
	public String getPassword() {
		return this.password;
	}

	@Override
	public String getUsername() {
		return this.loginName;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public String getLoginName() {
		return loginName;
	}

	public List<Role> getRoles() {
		return roles;
	}

	@Override
	public String toString() {
		return "SecurityUser [id=" + id + ", name=" + name + ", loginName=" + loginName + "]";
	}

	public List<String> getDataPermissions() {
		return dataPermissions;
	}

	public void setDataPermissions(List<String> dataPermissions) {
		this.dataPermissions = dataPermissions;
	}

	public String getDataPermissionStr() {
		if (Collections3.isEmpty(dataPermissions)) {
			return "";
		}
		return Joiner.on(",").join(dataPermissions);
	}

}
